package com.pennysaver.dao.mysql;

import java.sql.*;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/*
 * TODO: This should be a singleton
 * http://dev.mysql.com/tech-resources/articles/connection_pooling_with_connectorj.html
 * http://stackoverflow.com/questions/2299469/how-should-i-connect-to-a-mysql-data-source-from-eclipse
 * my sql jar should be at TOMCAT_HOME/common/lib
 */
public class MySqlConnection {

	DataSource dataSource;

	private MySqlConnection() {
		try {
			dataSource = (DataSource) new InitialContext()
					.lookup("java:comp/env/" + "jdbc/db");
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * SingletonHolder is loaded on the first execution of
	 * Singleton.getInstance() or the first access to SingletonHolder.INSTANCE,
	 * not before.
	 */
	private static class MySqlConnectionHolder {
		public static final MySqlConnection INSTANCE = new MySqlConnection();
	}

	private static Connection getConnection() {
		try {
			return MySqlConnectionHolder.INSTANCE.dataSource.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static Boolean executeQuery(String query) {
		try {

			java.sql.PreparedStatement st = getConnection().prepareStatement(
					query);
			return st.execute();

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
